package HTTP

import (
	"io"
	"net/http"
	"os"
)

func upload(w http.ResponseWriter, req *http.Request) {
	var (
		code   int         = Success
		msg    string      = ""
		result interface{} = nil
	)
	defer func() {
		writeResponse(code, msg, result, w)
	}()

	err := req.ParseMultipartForm(32 << 20)
	if err != nil {
		code = errParseMultiForm
		msg = err.Error()
		return
	}
	icon, handler, err := req.FormFile("icon")
	if err != nil {
		code = errFormFile
		msg = err.Error()
		return
	}
	defer icon.Close()
	filePath := "uploadIcon/" + handler.Filename
	iconFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		code = errOpenFile
		msg = err.Error()
		return
	}
	defer iconFile.Close()
	n, err := io.Copy(iconFile, icon)
	if err != nil {
		code = errCopyFile
		msg = err.Error()
		return
	}
	if n > (20 << 20) {
		code = errRequestEntityTooLarge
		msg = "上传文件不要超过20M"
		os.Remove(filePath)
		return
	}
	code = Success
	msg = ""
	return
}
